<template>
  <div class="publish-page">
    <div class="container">
      <!-- 头部 -->
      <div class="page-header">
        <h1 class="page-title">发布动态</h1>
        <div class="header-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="publishing" @click="handlePublish">
            发布
          </el-button>
        </div>
      </div>

      <!-- 表单 -->
      <div class="publish-form">
        <!-- 标题（可选） -->
        <div class="form-item">
          <el-input
            v-model="form.title"
            placeholder="给你的动态起个标题吧（选填）"
            maxlength="100"
            show-word-limit
            size="large"
          />
        </div>

        <!-- 内容 -->
        <div class="form-item">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="8"
            placeholder="分享你的旅行故事..."
            maxlength="2000"
            show-word-limit
          />
        </div>

        <!-- 图片上传 -->
        <div class="form-item">
          <div class="upload-section">
            <el-upload
              v-model:file-list="fileList"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleImageChange"
              :on-remove="handleImageRemove"
              :limit="9"
              accept="image/*"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">最多上传9张图片</div>
          </div>
        </div>

        <!-- 位置 -->
        <div class="form-item">
          <el-input
            v-model="form.location"
            placeholder="添加位置"
            size="large"
          >
            <template #prefix>
              <el-icon><Location /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 标签 -->
        <div class="form-item">
          <label class="form-label">添加标签</label>
          <div class="tags-input">
            <el-tag
              v-for="tag in form.tags"
              :key="tag"
              closable
              @close="handleRemoveTag(tag)"
              class="tag-item"
            >
              #{{ tag }}
            </el-tag>
            <el-input
              v-if="tagInputVisible"
              ref="tagInputRef"
              v-model="tagInputValue"
              size="small"
              class="tag-input"
              @keyup.enter="handleAddTag"
              @blur="handleAddTag"
            />
            <el-button
              v-else
              size="small"
              @click="showTagInput"
              class="add-tag-btn"
            >
              + 添加标签
            </el-button>
          </div>
        </div>

        <!-- 类型选择 -->
        <div class="form-item">
          <label class="form-label">动态类型</label>
          <el-radio-group v-model="form.type">
            <el-radio label="travel">游记</el-radio>
            <el-radio label="photo">摄影</el-radio>
            <el-radio label="qa">问答</el-radio>
            <el-radio label="other">其他</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Location } from '@element-plus/icons-vue'
// import { createCommunityPost, uploadImage } from '@/api/travel/index.js'

const router = useRouter()

const publishing = ref(false)
const fileList = ref([])
const tagInputRef = ref(null)
const tagInputVisible = ref(false)
const tagInputValue = ref('')

// 表单数据
const form = ref({
  title: '',
  content: '',
  images: [],
  location: '',
  tags: [],
  type: 'travel'
})

// 图片变化
const handleImageChange = (file) => {
  // TODO: 上传图片
  // const url = await uploadImage(file.raw)
  // form.value.images.push(url)
  
  // 模拟上传
  const url = URL.createObjectURL(file.raw)
  form.value.images.push(url)
}

// 移除图片
const handleImageRemove = (file) => {
  const index = fileList.value.findIndex(f => f.uid === file.uid)
  if (index > -1) {
    form.value.images.splice(index, 1)
  }
}

// 显示标签输入框
const showTagInput = () => {
  if (form.value.tags.length >= 5) {
    ElMessage.warning('最多添加5个标签')
    return
  }
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 添加标签
const handleAddTag = () => {
  const tag = tagInputValue.value.trim()
  if (tag && !form.value.tags.includes(tag)) {
    if (form.value.tags.length >= 5) {
      ElMessage.warning('最多添加5个标签')
    } else {
      form.value.tags.push(tag)
    }
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 移除标签
const handleRemoveTag = (tag) => {
  form.value.tags = form.value.tags.filter(t => t !== tag)
}

// 取消
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消吗？未保存的内容将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '继续编辑',
    type: 'warning'
  }).then(() => {
    router.back()
  }).catch(() => {})
}

// 发布
const handlePublish = async () => {
  // 表单验证
  if (!form.value.content.trim()) {
    ElMessage.warning('请输入动态内容')
    return
  }

  publishing.value = true
  try {
    // TODO: 调用API
    // await createCommunityPost(form.value)
    
    // 模拟发布
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('发布成功！')
    router.push('/community')
  } catch (error) {
    ElMessage.error('发布失败，请重试')
  } finally {
    publishing.value = false
  }
}
</script>

<style scoped lang="less">
.publish-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 32px 0 80px;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 24px;
}

// 页面头部
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 24px 32px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

// 表单
.publish-form {
  background: #fff;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.form-item {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 15px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 12px;
}

// 图片上传
.upload-section {
  :deep(.el-upload-list) {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  :deep(.el-upload--picture-card) {
    width: 120px;
    height: 120px;
    border-radius: 8px;
  }

  :deep(.el-upload-list__item) {
    width: 120px;
    height: 120px;
    border-radius: 8px;
  }
}

.upload-tip {
  font-size: 13px;
  color: #999;
  margin-top: 8px;
}

// 标签输入
.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  font-size: 14px;
  background: rgba(255, 107, 107, 0.1);
  color: #ff6b6b;
  border: none;
}

.tag-input {
  width: 120px;
}

.add-tag-btn {
  border-style: dashed;
}

// 响应式
@media (max-width: 768px) {
  .publish-page {
    padding: 20px 0 60px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    padding: 20px;
  }

  .header-actions {
    width: 100%;

    .el-button {
      flex: 1;
    }
  }

  .publish-form {
    padding: 24px 20px;
  }

  .upload-section {
    :deep(.el-upload--picture-card),
    :deep(.el-upload-list__item) {
      width: 100px;
      height: 100px;
    }
  }
}
</style>
